<template>
  <a-modal :title="title" :width="width" style="top: 0" :bodyStyle="bodyStyle" :visible="visible" :maskClosable="false"
    :forceRender="true" :confirmLoading="confirmLoading" @ok="handleSubmit" @cancel="handleCancel" cancelText="关闭">
    <template slot="footer">
      <a-button key="back" @click="handleCancel" :loading="confirmLoading">关闭</a-button>
      <a-button v-if="title != '详情'" key="submit" type="primary" @click="handleSubmit" :loading="confirmLoading">确认
      </a-button>
    </template>

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <j-form-container :disabled="disableSubmit">
        <a-divider dashed orientation="left">账号信息</a-divider>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item label="用户账号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入用户账号" v-decorator="['username', validatorRules.username]" :readOnly="!!model.id" />
            </a-form-item>
          </a-col>
          <a-col :span="8" v-if="title == '新增'">
            <a-form-item label="登陆密码" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input type="password" placeholder="请输入登陆密码" v-decorator="['password', validatorRules.password]" />
            </a-form-item>
          </a-col>
          <a-col :span="8" v-if="title == '新增'">
            <a-form-item label="确认密码" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input type="password" @blur="handleConfirmBlur" placeholder="请重新输入登陆密码"
                v-decorator="['confirmpassword', validatorRules.confirmpassword]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="姓名">
              <a-input placeholder="请输入姓名" v-decorator="['realname', validatorRules.realname]" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="性别">
              <a-select placeholder="请选择性别" v-decorator="['sex', {}]">
                <a-select-option v-for="item in sexList" :key="item.value">{{ item.text }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="民族" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入民族" v-decorator="['national', {}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item label="出生日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-date-picker style="width: 100%" placeholder="请选择出生日期" format="YYYY-MM-DD" v-decorator="['birthday', {}]"
                @change="computedAge" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="年龄" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number placeholder="请输入年龄" v-model="age" :min="0" style="width: 100%" disabled />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="手机号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入手机号" v-decorator="['phone', validatorRules.phone]" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item label="角色分配" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select mode="multiple" style="width: 100%" placeholder="请选择用户角色" @change="handleSelectedRole"
                v-decorator="['selectedRole', validatorRules.selectedRole]">
                <a-select-option v-for="(role, roleindex) in roleList" :key="roleindex.toString()" :value="role.id">
                  {{ role.roleName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="部门分配" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-search placeholder="点击右侧按钮选择部门"
                v-decorator="['checkedDepartNameString', validatorRules.checkedDepartNameString]" @search="onSearch" readOnly>
                <a-button slot="enterButton" icon="search">选择</a-button>
              </a-input-search>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="头像" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-upload
                listType="picture-card"
                class="avatar-uploader"
                :showUploadList="false"
                :action="uploadAction"
                :data="{ isup: 1 }"
                :headers="headers"
                :beforeUpload="beforeUpload"
                @change="handleChangeUf"
              >
                <img v-if="picUrlUf" :src="getAvatarViewUf()" alt="头像" style="height: 104px; max-width: 200px" />
                <div v-else>
                  <a-icon :type="uploadLoadingUf ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">上传</div>
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item label="冻结状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="radio" v-decorator="['status', { initialValue: '1' }]" :trigger-change="true"
                dict-code="user_status"></j-dict-select-tag>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="工作流引擎" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag v-decorator="['activitiSync', { initialValue: '1' }]" placeholder="请选择是否同步工作流引擎"
                :type="'radio'" :triggerChange="true" dictCode="activiti_sync" />
            </a-form-item>
          </a-col>
        </a-row>
      </j-form-container>
      </a-form>
    </a-spin>
    <depart-window ref="departWindow" @ok="modalFormOk"></depart-window>
  </a-modal>
</template>

<script>
import { httpAction, getAction, putAction } from '@/api/manage'
import pick from 'lodash.pick'
import moment from 'moment'
import JDate from '@/components/jeecg/JDate'
import JMonth from '@/components/jeecg/JMonth'
import Vue from 'vue'
// 引入搜索部门弹出框的组件
import departWindow from './DepartWindow'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { initDictOptions, filterDictText } from '@/components/dict/JDictSelectUtil'
import { addUser, editUser, queryUserRole, queryall, checkUsername } from '@/api/api'
import JEllipsis from '../../../components/jeecg/JEllipsis'
import debounce from 'lodash/debounce'
export default {
  name: 'PersonnelModal',
  components: {
    JEllipsis,
    JDate,
    JMonth,
    departWindow,
  },
  data() {
    this.handleSubmit = debounce(this.handleSubmit, 800, { leading: true, trailing: false }) //消抖
    return {
      selectedDepartKeys: [],
      checkedDepartKeys: [],
      checkedDepartNames: [],
      checkedDepartNameString: '', // 保存部门的名称 =>title
      showDepartTip: false,
      selectedRoleId: [],
      uploadLoadingUf: false,
      disableSubmit: false,
      userDepartModel: { userId: '', departIdList: [] }, // 保存SysUserDepart的用户部门中间表数据需要的对象
      roleList: [],
      selectDepart: [],
      selectedRole: [],
      title: '操作',
      width: window.innerWidth * 0.8,
      bodyStyle: {
        padding: '0 24px',
        top: '0',
        overflow: 'hidden',
      },
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        realname: { rules: [{ required: true, message: '请输入姓名!' }] },
        username: {
          rules: [
            {
              required: true,
              message: ' ',
            },
            {
              validator: this.validateUsername,
            },
          ],
          validateTrigger: ['blur'],
        },
        password: {
          rules: [
            {
              required: true,
              message: '请输入密码!',
            },
            {
              validator: this.validateToNextPassword,
            },
          ],
          validateTrigger: ['blur'],
        },
        confirmpassword: {
          rules: [
            {
              required: true,
              message: '请重新输入登陆密码!',
            },
            {
              validator: this.compareToFirstPassword,
            },
          ],
          validateTrigger: ['blur'],
        },
        age: { rules: [{ required: false, message: '请输入年龄!' }] },
        sex: { rules: [{ required: false, message: '请选择性别!' }] },
        selectedRole: { rules: [{ required: true, message: '请选择角色分配!' }] },
        checkedDepartNameString: { rules: [{ required: true, message: '请选择部门分配!' }] },
      },
      url: {
        add: '/personnel/personnel/add',
        edit: '/personnel/personnel/edit',
        fileUpload: window._CONFIG['domianURL'] + '/sys/common/upload',
        imgerver: window._CONFIG['domianURL'] + '/sys/common/view',
        getById: '/personnel/personnel/getStaffInfo',
        userId: '/sys/user/generateUserId', // 引入生成添加用户情况下的url
        userWithDepart: '/sys/user/userDepartList', // 引入为指定用户查看部门信息需要的url
        addUDepartIds: '/sys/user/addUDepartIds', // 引入为用户添加部门信息需要的url
        editUDepartIds: '/sys/user/editUDepartIds', // 引入为用户更新部门信息需要的url
        syncUserByUserName: '/process/extActProcess/doSyncUserByUserName', //同步用户到工作流
      },
      headers: {},
      age: '',
      picUrlUf: '',
      dateFormat: 'YYYY-MM-DD',
      showRoleTip: false,
      sexList: [],
      activeKey: '1',
    }
  },
  created() {
    const token = Vue.ls.get(ACCESS_TOKEN)
    this.headers = { 'X-Access-Token': token }
  },
  computed: {
    uploadAction: function () {
      return this.url.fileUpload
    },
  },
  watch: {
    selectedRole(val) {
      if (val) {
        this.showRoleTip = false
      } else {
        this.showRoleTip = true
      }
    },
    checkedDepartNameString(val) {
      if (val) {
        this.showDepartTip = false
      } else {
        this.showDepartTip = true
      }
    },
    dateRange(val) {
      if (val == []) {
        this.dateRangeFlag = true
      } else {
        this.dateRangeFlag = false
      }
    },
  },
  methods: {
    validateUsername(rule, value, callback) {
      if (value) {
        if (/[\u4E00-\u9FA5]/g.test(value)) {
          callback('账号不能输入汉字!')
        } else {
          var params = {
            id: this.model.id,
            username: value,
          }
          checkUsername(params).then((res) => {
            if (res.success) {
              callback()
            } else {
              callback('用户账号已存在！')
            }
          })
        }
      } else {
        callback('请输入用户账号！')
      }
    },
    computedAge(e) {
      if(e) {
        this.age = new Date().getFullYear() - moment(e).format('YYYY')
      } else {
        this.age = null
      }
    },
    compareToFirstPassword(rule, value, callback) {
      const form = this.form
      if (value && value !== form.getFieldValue('password')) {
        callback('两次输入的密码不一样！')
      } else {
        callback()
      }
    },
    validateToNextPassword(rule, value, callback) {
      //密码长度不少于6位，并且至少有一个大写字母或小写字母，至少有一个数字，至少有一个特殊字符包括  ‘  -`=;',.~!@#$%^&*()_+|{}:"?  ’
      if (
        !value 
        // new RegExp(
        //   /^(?![0-9A-Za-z]+$)(?![-`=\[\];',.~!@#$%^&*()_+|{}:"?]+$)(?![0-9-`=\[\];',.~!@#$%^&*()_+|{}:"?]+$)(?![A-Za-z-`=\[\];',.~!@#$%^&*()_+|{}:"?]+$)[0-9a-zA-Z-`=\[\];',.~!@#$%^&*()_+|{}:"?]{6,}$/
        // ).test(value)
      ) {
        const confirmpassword = this.form.getFieldValue('confirmpassword')
        if (value && confirmpassword && value !== confirmpassword) {
          callback('两次输入的密码不一样！')
        }
        if (value && this.confirmDirty) {
          this.form.validateFields(['confirm'], { force: true })
        }
        callback()
      } else {
        // callback('密码由数字、字母、特殊字符组合构成且长度不少于6位！')
        callback()
      }
    },
    handleConfirmBlur(e) {
      const value = e.target.value
      this.confirmDirty = this.confirmDirty || !!value
    },
    handleSelectedRole(val) {
      this.selectedRole = val
    },
    // 同步用户信息
    updateUserMsg(record) {
      putAction(this.url.syncUserByUserName, { userName: record }).then((res) => {
        console.log(res.message)
      })
    },
    handleChangeUf(info) {
      this.picUrlUf = ''
      if (info.file.status === 'uploading') {
        this.uploadLoadingUf = true
        return
      }
      if (info.file.status === 'done') {
        var response = info.file.response
        this.uploadLoadingUf = false
        // console.log(response)
        if (response.success) {
          this.model.avatar = response.message
          this.picUrlUf = 'Has no pic url yet'
        } else {
          this.$message.warning(response.message)
        }
      }
    },
    getAvatarViewUf() {
      return this.url.imgerver + '/' + this.model.avatar
    },
    handleSubmit() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          if (this.checkedDepartNameString === '') {
            this.$message.warning('请选择部门!')
            this.showDepartTip = true
            return
          }
          if (this.selectedRole.length <= 0) {
            this.showRoleTip = true
            this.$message.warning('请选择角色!')
            return
          }
          let formData = Object.assign(this.model, values)
          that.confirmLoading = true
          //部门和角色赋值
          formData.selectedroles = this.selectedRole.length > 0 ? this.selectedRole.join(',') : ''
          formData.departId = this.selectedDepartKeys.length > 0 ? this.selectedDepartKeys.join(',') : ''
          if (!formData.birthday) {
            formData.birthday = ''
          } else {
            //生日默认为中午12点 避免夏令制问题出现
            formData.birthday = formData.birthday.format('YYYY-MM-DD') + ' 12:00:00'
          }
          let obj
          console.log('提交参数', formData)
          if (!this.model.id) {
            obj = addUser(formData)
          } else {
            obj = editUser(formData)
          }
          obj.then((res) => {
            if (res.success) {
              that.addDepartsToUser(that, res.result.id,formData) 
            } else {
              that.confirmLoading = false
              that.$message.warning(res.message)
            }
          })
        }
      })
    },
    // 根据当前用户添加部门信息的方法
    addDepartsToUser(that, id, formData) {
      let httpurl = ''
      let method = ''
      if (this.title === '新增') {
        this.userDepartModel.userId = id
        httpurl += this.url.addUDepartIds
        method = 'post'
      } else {
        httpurl += this.url.editUDepartIds
        method = 'put'
      }
      httpAction(httpurl, this.userDepartModel, method).then((res) => {
        if (res.success) {
          this.userDepartModel = {}
          that.updateUserMsg(formData.username)
          that.$emit('ok')
          that.$message.success(res.message)
          that.close()
        } else {
          that.confirmLoading = false
          that.$message.warning(res.message)
        }
      })
    },
    // 根据当前用户添加部门信息的方法（我的部门调用）
    addDepartsToUser1: function () {
      let httpurl = ''
      let method = ''
      httpurl += this.url.addUDepartIds
      method = 'post'
      let departIdList = []
      departIdList.push(this.deptId)
      httpAction(httpurl, { userId: this.userId, departIdList: departIdList }, method).then((res) => {
        if (res.success) {
          this.userId = ''
          this.deptId = ''
          this.departIdList = []
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    beforeUpload: function (file) {
      var fileType = file.type
      if (fileType.indexOf('image') < 0) {
        this.$message.warning('请上传图片')
        return false
      }
      //TODO 验证文件大小
    },
    //
    loadCheckedDeparts() {
      let that = this
      if (!that.userId) {
        return
      }
      getAction(that.url.userWithDepart, { userId: that.userId }).then((res) => {
        that.checkedDepartNames = []
        if (res.success) {
          this.selectDepart = res.result
          for (let i = 0; i < res.result.length; i++) {
            that.checkedDepartNames.push(res.result[i].title)
            that.checkedDepartKeys.push(res.result[i].key)
            that.selectedDepartKeys.push(res.result[i].key)
          }
          this.checkedDepartNameString = this.checkedDepartNames.join(',')
          this.$nextTick(() => {
            this.form.setFieldsValue({ 'checkedDepartNameString': this.checkedDepartNameString })
          })
        } else {
          console.log(res.message)
        }
      })
    },
    // 获取用户对应部门弹出框提交给返回的数据
    modalFormOk(formData) {
      this.checkedDepartNames = []
      this.selectedDepartKeys = []
      this.checkedDepartNameString = ''
      this.userId = formData.userId
      this.selectDepart = formData.departIdList
      this.userDepartModel.userId = formData.userId
      for (let i = 0; i < formData.departIdList.length; i++) {
        this.selectedDepartKeys.push(formData.departIdList[i].key)
        this.checkedDepartNames.push(formData.departIdList[i].title)
        this.checkedDepartNameString = this.checkedDepartNames.join(',')
      }
      this.$nextTick(() => {
        this.form.setFieldsValue({ 'checkedDepartNameString': this.checkedDepartNameString })
      })
      this.userDepartModel.departIdList = this.selectedDepartKeys
    },
    // 搜索用户对应的部门API
    onSearch(selectedRole) {
      this.$refs.departWindow.add(this.selectedDepartKeys, this.userId,this.selectDepart)
    },
    loadUserRoles(userid) {
      queryUserRole({ userid: userid }).then((res) => {
        if (res.success) {
          this.selectedRole = res.result
          this.form.setFieldsValue({ selectedRole: this.selectedRole })
        } else {
        }
      })
    },
    initialRoleList() {
      queryall().then((res) => {
        if (res.success) {
          this.roleList = res.result
        } else {
          console.log(res.message)
        }
      })
    },
    add() {
      this.edit({})
    },
    edit(record) {
      this.activeKey = '1'
      //详情、编辑 回显需要调接口获取数据再回显 yj ljl
      if (this.title !== '新增') {
        this.getInfoById(record.id)
      } else {
        this.getInfoNormal(record)
      }
    },
    getInfoNormal(record) {
      this.visible = true
      this.getSelectList()
      this.record = record
      this.showRoleTip = false
      this.showDepartTip = false
      this.initialRoleList()
      this.userId = record.id ? record.id : ''
      this.model = Object.assign({}, record)
      if (record.hasOwnProperty('id')) {
        //角色回显
        this.loadUserRoles(record.id)
        //单独处理冻结状态字段 转字符串类型，否则编辑详情不会回显状态
        this.model.status = this.model.status.toString()
        if(record.avatar) {
          this.picUrlUf = 'hase pic'
        }
      }
      this.$nextTick(() => {
        this.form.setFieldsValue(
          pick(
            this.model,
            'username',
            'password',
            'confirmpassword',
            'status',
            'activitiSync',
            'realname',
            'sex',
            'national',
            'birthday',
            'phone',
            'selectedRole'
          )
        )
        if (record.id) {
          this.form.setFieldsValue({ sex: this.model.sex ? this.model.sex.toString() : '' })
          if (record.birthday) {
            this.age = new Date().getFullYear() - moment(record.birthday).format('YYYY')
          }
          this.form.setFieldsValue({ birthday: record.birthday == null ? null : moment(record.birthday) })
          this.loadCheckedDeparts()
        }
      })
    },
    //详情\编辑 回显需要调接口获取数据再回显 yj ljl
    getInfoById(id) {
      this.visible = true
      this.confirmLoading = true
      getAction('/sys/user/queryById', { id: id })
        .then((res) => {
          if (res.success) {
            this.getInfoNormal(res.result)
          } else {
            this.$message.warning(res.message)
            this.getInfoNormal({})
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    close() {
      this.$emit('close')
      this.confirmLoading = false
      this.visible = false
      this.form.resetFields()
      this.checkedDepartNameString = ''
      this.showRoleTip = false
      this.showDepartTip = false
      this.selectedRoleId = ''
      this.selectedRole = []
      this.userDepartModel = {}
      this.checkedDepartNames = []
      this.selectedDepartKeys = []
      this.checkedDepartKeys = []
      this.sex = ''
      this.age = ''
      this.activeKey = '1'
      this.disableSubmit = false
      this.picUrlUf = ''
    },
    getSelectList() {
      //性别
      initDictOptions('sex').then((res) => {
        if (res.success) {
          this.sexList = res.result
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    handleCancel() {
      this.close()
    },
    moment,
  },
}
</script>

<style lang="less" scoped>
.tiptext {
  display: inline-block;
  position: absolute;
  color: #f5222d;
  left: 0px;
  top: 20px;
  width: 300px;
}

.tooltipStyle {
  display: inline-block;
  margin-right: 4px;
  font-family: SimSun;
  line-height: 1;
  font-size: 14px;
  color: #1890ff;
  margin-left: 5px;
  width: 20px;
  cursor: pointer;
}

.defaultFileBox {
  position: relative;
  width: 100%;
  height: 39px;
  overflow: hidden;
}

.deleteFile {
  position: absolute;
  top: 40%;
  right: 0;
  font-size: 11px;
}

.defaultFile {
  width: 90%;
  height: 39px;
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.defaultFileBox:hover {
  color: #1890ff;
}

.notNone /deep/ label:before {
  display: inline-block;
  margin-right: 4px;
  color: #f5222d;
  font-size: 14px;
  font-family: SimSun, sans-serif;
  line-height: 1;
  content: '*';
}

#templateBox {
  margin-bottom: 20px;
}

#templateBox .ant-form-item {
  margin-bottom: 0px;
}

.model-view {
  height: 45px;
  border-bottom: 1px dashed #e8e8e8;
  font-size: 22px;
  margin-bottom: 20px;
}

.publicFlex {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-around;

  i {
    cursor: pointer;
  }

  i:hover {
    color: #1890ff;
  }
}
</style>